<template>
  <t-layout style="height: 100vh">
    <t-aside>
      <t-menu :value="activeMenuValue" @change="handleChange" theme="dark">
        <template #logo>
          <img height="56" :src="BMSLogo" alt="logo" />
        </template>
        <t-submenu v-for="item in pageData.menuData" :value="item.code" :key="item.id" :title="item.name">
          <t-menu-item v-for="_item in item.children" :key="_item.id" :value="_item.code">{{ _item.name }}</t-menu-item>
          <template #icon>
            <t-icon :name="item.pcIcon" />
          </template>
        </t-submenu>
      </t-menu>
    </t-aside>
    <t-layout>
      <t-header>
        <t-head-menu theme="light">
          <t-breadcrumb :max-item-width="'150'">
            <t-breadcrumb-item :to="item.path" v-for="item in routeMenu" :key="item.name">
              {{ item.meta.title }}
            </t-breadcrumb-item>
          </t-breadcrumb>
          <template #operations>
            <!-- <b-message /> -->
            <t-button variant="text" @click="handleColorModeChange()">
              <template #icon><t-icon :name="pageData.colorModeIcon" /></template>
              {{ pageData.colorModeText }}
            </t-button>
            <t-dropdown :options="pageData.userOptions" @click="clickUserHandler">
              <t-button variant="text">
                <template #icon><t-icon name="user-circle" /></template>
                当前用户：{{ pageData.userData?.realName }}
              </t-button>
            </t-dropdown>
          </template>
        </t-head-menu>
      </t-header>
      <t-content style="height: calc(100vh - 40px); padding: 1.2rem; overflow: auto">
        <div style="width: 80vw">
          <t-loading :loading="menuStore.menuLoading" text="正在载入页面...">
            <RouterView />
          </t-loading>
        </div>
      </t-content>
    </t-layout>
  </t-layout>
</template>

<script lang="ts" setup>
import { computed, defineAsyncComponent, reactive, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import { MessagePlugin, NotifyPlugin } from "tdesign-vue-next";

import BMSLogo from "@/assets/logo.png";

const BMessage = defineAsyncComponent(() => import("@/pages/Dashboard/components/Message/index.vue"));

import { useMenuStore } from "@/stores/modules/menu";
import { useUserStore } from "@/stores/modules/user";

const route = useRoute();
const router = useRouter();

const menuStore = useMenuStore();
const userStore = useUserStore();

const routeMenu = computed(() => {
  return route.matched;
});

const pageData = reactive<Record<string, any>>({
  userOptions: [
    {
      content: "退出登录",
      value: "logout"
    }
  ],
  menuData: [],
  userData: {},
  colorModeIcon: "",
  colorModeText: ""
});

// 菜单变化时候的点击
const handleChange = (e: string) => {
  try {
    menuStore.activeMenu = e;
    router.push({ name: e });
  } catch (error) {
    MessagePlugin.error("所选菜单页面不存在或相关路由发生异常，请打开浏览器开发者工具以获取更多信息。");
    console.error(error);
  }
};

const activeMenuValue = computed(() => {
  return menuStore.activeMenu;
});

const clickUserHandler = (e: Record<string, any>) => {
  if (e.value === "logout") {
    window.sessionStorage.removeItem("userAuthToken");
    window.localStorage.removeItem("userAuthToken");
    userStore.setUserData(null);
    menuStore.setActiveMenu(null);
    menuStore.setMenuData(null);
    NotifyPlugin.warning({ title: "提示", content: "已经退出登录。" });
    router.push("/auth/login");
  }
};

const handleColorModeChange = () => {
  if (pageData.colorModeIcon === "moon") {
    menuStore.setColorMode("dark");
    getColorMode();
  } else if (pageData.colorModeIcon === "sunny") {
    menuStore.setColorMode("light");
    getColorMode();
  } else {
    MessagePlugin.error("未知的颜色标识！");
  }
};

const getColorMode = () => {
  const colorMode = menuStore.colorMode;

  requestAnimationFrame(() => {
    if (colorMode === "dark") {
      document.documentElement.setAttribute("theme-mode", "dark");
      pageData.colorModeIcon = "sunny";
      pageData.colorModeText = "进入浅色模式";
    } else {
      document.documentElement.removeAttribute("theme-mode");
      pageData.colorModeIcon = "moon";
      pageData.colorModeText = "进入深色模式";
    }
  });
};

pageData.menuData = menuStore.menuData;
pageData.userData = userStore.userData;

// 动态监听菜单变化
watch(
  () => menuStore.menuData,
  (newMenuData: Record<string, any>) => {
    pageData.menuData = newMenuData;
  }
);

// 动态监听用户变化
// watch(
//   () => userStore.userData,
//   (newUserData: Record<string, any>) => {
//     pageData.userData = newUserData;
//   }
// );

getColorMode();
</script>
